package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.Blog;
import dao.BlogDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BlogDao blogDao = new BlogDao();
        String blogId = req.getParameter("blogId");

        if (blogId == null){
            //说明此时要获取的是博客列表
            List<Blog> blogs = blogDao.getBlogs();
            String respJson = objectMapper.writeValueAsString(blogs);
            resp.setContentType("application/json; charset = utf8");
            resp.getWriter().write(respJson);
        }else {
            try {
                Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
                if (blog == null){
                    //返回一个id为0的blog对象，前端再根据这里进行判定
                    blog = new Blog();
                }
                String respJson = objectMapper.writeValueAsString(blog);
                resp.setContentType("application/json; charset = utf8");
                resp.getWriter().write(respJson);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
